package com.cetcs.kmga.dataManager.util.socket;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class MsgService {

    private static final Logger logger = LoggerFactory.getLogger(MsgService.class);
    //线程池
    private ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * 发送消息
     *
     * @param userId 接收人消息ID
     * @param msg    消息内容
     * @throws Exception
     */
    public void publishMsg(String userId, String msg) throws Exception {
        logger.info("监听到有新消息添加。。。");
        //启动线程
        if (StringUtils.isNotBlank(msg)) {
            //立即推送
            executorService.execute(new AfterConnectionEstablishedTask(userId, msg));
        }
    }

    /**
     * @param userId
     * @throws Exception
     */
    public void afterConnectionEstablished(String userId) throws Exception {
        logger.info("建立websocket连接后推送新消息。。。");
        String message = "";
        if (StringUtils.isNotBlank(userId)) {
            executorService.execute(new AfterConnectionEstablishedTask(userId, message));
        }
    }

}
